package com.charles.core.generator;


import com.charles.entity.IdBlock;
import com.charles.service.IdBlockService;

import java.util.concurrent.atomic.AtomicLong;

public class DbIdGenerator implements UIdGenerator {

    private String bizType;

    private IdBlockService getNextIdBlockCmd;

    public DbIdGenerator(IdBlockService getNextIdBlockCmd, String bizType) {
        this.getNextIdBlockCmd = getNextIdBlockCmd;
        this.bizType = bizType;
    }

    private volatile IdBlock idBlock = new IdBlock(new AtomicLong(0), -1);

    @Override
    public Long nextId() {
        /**
         * id的比较可以放在idBlock里面比较，getNextId也从Segment里面去
         */
        loadCurrent();
        return idBlock.nextId();
    }

    public synchronized void loadCurrent() {
        if (!idBlock.useful()) {
            idBlock = getNewBlock();
        }
    }

    private IdBlock getNewBlock() {
        return getNextIdBlockCmd.getIdBlock(bizType);
    }
}